<template>
  <div>
    <!-- 查询条件 -->
    <el-form :model="ruleForm" ref="form" :rules="rules">
      <el-row :gutter="20">
        <el-col :span="6" :offset="0">
          <el-form-item label="供应商:" prop="organId">
            <el-select v-model="ruleForm.organId" placeholder="选择供应商"
            v-bind:disabled="!!ruleForm.linkNumber">
              <el-option
                v-for="item in suppliers"
                :key="item.supId"
                :label="item.supName"
                :value="item.supId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" :offset="0">
          <el-form-item label="单据日期:" prop="billDate">
            <el-date-picker
              type="datetime"
              v-model="ruleForm.billDate"
              placeholder="选择日期与时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              clearable
              class="input"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6" :offset="0">
          <el-form-item label="单据编号:">
            <el-input v-model="ruleForm.number" readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" :offset="0">
          <el-form-item label="关联订单">
            <el-input v-model="ruleForm.linkNumber" readonly suffix-icon="Search" placeholder="请选择关联订单"
            v-perm:sale:sale_in:insert:associateorder="handleIconClick" />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="ant-row-flex" style="display: flex; align-items: center">
        <div class="ant-col" style="margin-right: 10px">
          <el-button
            type="primary"
            @click="insertTr"
            class="ant-btn ant-btn-primary"
            v-if="!ruleForm.linkNumber"
          >
            <el-icon class="el-icon-left">
              <Plus />
            </el-icon>
            <span>插入行</span>
          </el-button>
        </div>
        <div class="ant-col" style="margin-right: 10px">
          <el-button plain v-if="!ruleForm.linkNumber">扫码录入</el-button>
        </div>
        <div class="ant-col" style="margin-right: 10px">
          <el-button>
            <el-icon style="margin-right: 5px">
              <Clock />
            </el-icon>
            历史单据
          </el-button>
        </div>
      </div>
    <!-- 选项表格 -->
    <el-table
      class="my-custom-table"
      :data="tableData"
      show-summary
      :summary-method="getSummaries"
      max-height="340"
    >
      <el-table-column type="selection" width="30" />
      <el-table-column label="仓库名称" width="100" >
        <template #default="{ row }">
            <el-select v-model="row.depotId">
              <el-option v-for="item in depots"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
              </el-option>
            </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="barcode" label="条码" width="160">
        <template #default="{ row }">
          <el-input v-model="row.barCode">
            <template #append v-if="!ruleForm.linkNumber">
              <el-button
                v-perm:purchase:order:insert:materialInsert="Saleinorder"
                ><el-icon>
                  <Search /> </el-icon
              ></el-button>
            </template>
          </el-input>
        </template>
      </el-table-column>
      <el-table-column label="名称" width="160">
        <template #default="{ row }">
          <el-input v-model="row.name" class="dashed-input"> </el-input>
        </template>
      </el-table-column>
      <el-table-column label="规格" property="shopCode">
        <template #default="{ row }">
          <el-input v-model="row.standard" class="dashed-input"> </el-input>
        </template>
      </el-table-column>
      <el-table-column label="库存">
        <template #default="{ row }">
          <el-input v-model="row.kt" class="dashed-input">
          </el-input>
        </template>
      </el-table-column>
      <el-table-column label="单位">
        <template #default="{ row }">
          <el-input v-model="row.materialUnit" class="dashed-input">
          </el-input>
        </template>
      </el-table-column>
      <el-table-column label="多属性">
        <template #default="{ row }">
          <el-input v-model="row.sku" class="dashed-input"> </el-input>
        </template>
      </el-table-column>
      <el-table-column label="数量">
        <template #default="{ row }">
          <el-input  @input="change(row)" v-model="row.operNumber"> </el-input>
        </template>
      </el-table-column>
      <el-table-column label="单价">
        <template #default="{ row }">
          <el-input @input="change(row)" v-model="row.unitPrice"> </el-input>
        </template>
      </el-table-column>
      <el-table-column label="金额">
        <template #default="{ row }">
          <el-input  v-model="row.allPrice"> </el-input>
        </template>
      </el-table-column>
      <el-table-column label="税率">
        <template #default="{ row }">
          <el-input @input="change(row)" placeholder="%" v-model="row.taxRate"> </el-input>
        </template>
      </el-table-column>
      <el-table-column label="税额">
        <template #default="{ row }">
          <el-input v-model="row.taxMoney" class="dashed-input"> </el-input>
        </template>
      </el-table-column>
      <el-table-column label="价税合计">
        <template #default="{ row }">
          <el-input v-model="row.taxLastMoney"> </el-input>
        </template>
      </el-table-column>
      <el-table-column label="备注">
        <template #default="{ row }">
          <el-input v-model="row.remark"> </el-input>
        </template>
      </el-table-column>
    </el-table>
      <el-form-item style="margin-top: 5px">
        <el-input
          v-model="ruleForm.remark"
          :autosize="{ minRows: 1, maxRows: 4 }"
          type="textarea"
          placeholder="请输入备注"
        />
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="6" :offset="0">
          <el-form-item label="优惠率：">
            <el-input
              v-model="ruleForm.discountRate"
              placeholder="请输入优惠率"
            >
              <template #suffix>
                <span>%</span>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" :offset="0">
          <el-form-item label="付款优惠：">
            <el-input
              v-model="ruleForm.paymentDiscount"
              placeholder="请输入付款优惠"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" :offset="0">
          <el-form-item label="优惠后金额：">
            <el-input v-model="ruleForm.discountedAmount" readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" :offset="0">
          <el-form-item label="其它费用：">
            <el-input v-model="ruleForm.otherMoney" placeholder="请输入其它费用"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" :offset="0">
          <el-form-item label="结算账户：" prop="accountId">
            <el-select v-model="ruleForm.accountId" placeholder="选择结算账户">
              <el-option
                v-for="item in accounts"
                :key="item.accId"
                :label="item.name"
                :value="item.accId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" :offset="0">
          <el-form-item label="本次付款：">
            <el-input
              v-model="ruleForm.documentnumber"
              placeholder="请输入本次付款"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" :offset="0">
          <el-form-item label="本次欠款：">
            <el-input v-model="ruleForm.debt" readonly></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20" style="height: 30px">
        <el-col :span="24" :offset="0">
          <el-form-item style="float: right">
            <el-button @click="close">取消</el-button>
            <el-button @click="submitForm(form,1)">保存并审核</el-button>
            <el-button type="primary" @click="submitForm(form,0)">保存</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-dialog
      :destroy-on-close="true"
      :title="title"
      v-model="visible"
      width="65%"
      top="15vh"
      style="height: 750px"
    >
      <router-view
        @close="closeAdd"
        @saveSaleinorder="saveSaleinorder"
        :data="data"
      ></router-view>
    </el-dialog>
  </div>
</template>

<script setup>
// 导入Vue中的ref和defineEmits函数
import { ref, defineEmits, defineProps } from "vue";
// 使用defineEmits函数定义可以触发的自定义事件
import request from "@/api/request";
import router from "@/router";
import { Search } from "@element-plus/icons-vue";
import { ElMessage } from 'element-plus';

let data = defineProps([ "data" ])
let formData = data.data
let id = formData.id

let emits = defineEmits(["close"]);

let tableData = ref([{ 
    operNumber: 0,
    allPrice: 0,
    taxMoney: 0,
    taxLastMoney: 0
}]);

let title = ref("");

let form = ref();

let visible = ref(false);
//供应商
let suppliers = ref([]);
//结算用户
let accounts = ref([]);
//仓库
let depots = ref([]);
//单据信息
let ruleForm = ref({
  billDate: formData.operTime,
  organId: formData.supId,
  number: formData.number,
  remark: formData.remark,
  discountRate: formData.discount,
  paymentDiscount: formData.discountMoney,
  discountedAmount: formData.discountLastMoney,
  documentnumber: formData.changeAmount,
  accountId: formData.accountId,
  otherMoney: formData.otherMoney,
  debt: formData.debt,
  linkNumber: formData.linkNumber
});
//插入一条数据
let insertTr = () => {
  tableData.value.push({
    operNumber: 0,
    allPrice: 0,
    taxMoney: 0,
    taxLastMoney: 0
  });
};

//根据headerId查询子单据
let findById =()=>{
    request.get("/purchase/order/findById/"+ id)
    .then(resp => {
      console.log(resp.data)
        tableData.value = resp.data
    })
}
findById();

//校验规则
let rules = {
  organId: [
    { required: true, message: '请选择供应商！', trigger: 'change' }
  ],
  billDate: [
    { required: true, message: '请选择单据日期和时间！', trigger: 'change' }
  ],
  accountId: [
    { required: true, message: '请选择结算账户！', trigger: 'change' }
  ]
}

//表格合计
const getSummaries = (param) => {
  const { columns, data } = param;
  const sums = [];
  sums[0] = "合计";
  const operNumbers = data.map((item) => Number(item['operNumber']));
  const allPrices = data.map((item) => Number(item['allPrice']));
  const taxMoneys = data.map((item) => Number(item['taxMoney']));
  const taxLastMoneys = data.map((item) => Number(item['taxLastMoney']));
  let numberTotal = 0;
  let allPriceTotal = 0;
  let taxMoneyTotal = 0;
  let taxLastMoneyTotal = 0;
  operNumbers.forEach(item=>{
    numberTotal+=item
  })
  allPrices.forEach(item=>{
    allPriceTotal+=item
  })
  taxMoneys.forEach(item=>{
    taxMoneyTotal+=item
  })
  taxLastMoneys.forEach(item=>{
    taxLastMoneyTotal+=item
  })
  sums[8] = numberTotal
  sums[10] = allPriceTotal
  sums[12] = taxMoneyTotal
  sums[13] = taxLastMoneyTotal

  ruleForm.value.paymentDiscount = (ruleForm.value.discountRate*0.01) * taxLastMoneyTotal
  ruleForm.value.discountedAmount = taxLastMoneyTotal - ruleForm.value.paymentDiscount
  ruleForm.value.debt = Number(ruleForm.value.discountedAmount) + Number(ruleForm.value.otherMoney) - Number(ruleForm.value.documentnumber)
  return sums;
};

//input计算绑定
let change = (row)=>{
  row.allPrice = row.operNumber * row.unitPrice
  row.taxMoney = (row.taxRate*0.01) * row.allPrice
  row.taxLastMoney = row.taxMoney + row.allPrice
}

//关闭商品选择页面
let closeAdd = () => {
  visible.value = false;
};
let close = () => {
  emits("close");
};

//查询供应商
let findsuppliers = () =>{
  request({
    url:'/basic/vendor/findByStatus',
    method: 'get',
    params:{
      supType: 0
    }
  }).then(resp =>{
    suppliers.value = resp.data
  })
}
findsuppliers();

//查询仓库
let loadDepot = () => {
    request({
        url: '/basic/depot/findByEnabled',
        method: 'get'
    }).then(res => {
        depots.value = res.data;
    }).catch(err => {
        console.error(err);
    });
};
loadDepot();

//查询结算用户
let findaccounts = () => {
  request({
    url: "/basic/account/findByStatus",
    method: "get",
  }).then((resp) => {
    accounts.value = resp.data;
  });
};
findaccounts();

//弹出商品选择
let Saleinorder = (menu) => {
  title.value = menu.cname;
  visible.value = true;
  router.push(menu.path);
};

// 接收并显示保存的数据
let saveSaleinorder = (selectedItems) => {
  tableData.value = selectedItems.map((item) => ({
    barCode: item.barCode,
    categoryName: item.categoryName,
    color: item.color,
    commodityUnit: item.commodityUnit,
    materialName: item.materialName,
    mfrs: item.mfrs,
    model: item.model,
    sku: item.sku,
    standard: item.standard,
    totalIn: item.totalIn,
    remark: item.remark,
    totalOperNumber: item.totalOperNumber,
    totalOut: item.totalOut,
    unitPrice: item.unitPrice,
    basicnumber: item.basicnumber,
    allprice: item.allprice,
    mid: item.mid,
    aid: item.aid,
    operNumber: 1,
    allPrice: 1*item.unitPrice,
    taxRate: 0,//税率
    taxMoney: 0,//税额
    taxLastMoney: item.unitPrice//价税合计
  }));
};

//添加数据
const submitForm = (formEl,status) => {
  const requestData = {
    //主表添加数据
    erpDepotHead: {
      organId: ruleForm.value.organId,
      accountId: ruleForm.value.accountId,
      remark: ruleForm.value.remark,
      changeAmount: ruleForm.value.documentnumber,//支付定金
      totalPrice: tableData.value.reduce((total, row) => total + parseFloat(row.allPrice || 0),0), // 计算合计金额
      discount: ruleForm.value.discountRate,//优惠率
      discountMoney: ruleForm.value.paymentDiscount,//优惠金额
      discountLastMoney: ruleForm.value.discountedAmount,//优惠后金额
      status: status,
    },
    //附表添加数据
    erpDepotItems: tableData.value.map((row) => ({
      materialId: row.mid,
      materialExtendId: row.aid,
      materialUnit: row.commodityUnit,
      sku: row.sku,//多属性
      operNumber: row.operNumber,//数量
      basicNumber: row.operNumber,
      depotId: row.depotId,
      unitPrice: row.unitPrice,//单价
      allPrice: row.allPrice,
      remark: row.remark,
      taxRate: row.taxRate,//税率
      taxMoney: row.taxMoney,//税额
      taxLastMoney: row.taxLastMoney//价税合计
    })),
  };
  formEl.validate(valid =>{
    if(valid) {
      //发送请求
      request({
            url: '/sale/updateck',
            method: 'put',
            params: {number: ruleForm.value.number},
            data: requestData,
            headers: { 'Content-Type': 'application/json' }
        }).then(res => {
            close();
            ElMessage.success('提交成功');
        }).catch(err => {
            console.error(err);
            ElMessage.error('提交失败');
        });
      }
    })
};
</script>

<style scoped>
/* 增加表格单元格的内边距（上下左右都增加） */
::v-deep .el-table .cell {
  padding: 1px;
}

.my-custom-table .el-table__summary-row {
  /* 这里的样式将只应用于具有 my-custom-table 类的表格的合计行 */
  background-color: white;
  /* 示例背景色 */
}

.dashed-input {
  user-select: none;
  /* 禁止文本选择 */
  pointer-events: none;
  /* 禁止交互，如点击 */
}
</style>
